package com.moyuxi.sound_of_the_forest.ui.route

import android.app.AlertDialog
import android.os.Build
import androidx.activity.compose.BackHandler
import androidx.annotation.RequiresApi
import androidx.compose.material3.DrawerValue
import androidx.compose.material3.rememberDrawerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import androidx.core.os.bundleOf
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.moyuxi.sound_of_the_forest.MainActivity
import com.moyuxi.sound_of_the_forest.entity.LocalMusicBean
import com.moyuxi.sound_of_the_forest.service.AudioService
import com.moyuxi.sound_of_the_forest.ui.compose.AlbumOrArtistListInfoComponent
import com.moyuxi.sound_of_the_forest.ui.compose.SideDrawerCompose
import com.moyuxi.sound_of_the_forest.ui.pages.AboutMeScreen
import com.moyuxi.sound_of_the_forest.ui.pages.ApplicationErrorScreen
import com.moyuxi.sound_of_the_forest.ui.pages.ScanMusicScreen
import com.moyuxi.sound_of_the_forest.ui.pages.musicClassify.AlbumListFrameCompose
import com.moyuxi.sound_of_the_forest.ui.pages.musicClassify.ArtistListFrameCompose
import com.moyuxi.sound_of_the_forest.ui.pages.musicClassify.MusicClassifyScreen
import com.moyuxi.sound_of_the_forest.ui.pages.musicClassify.MusicListFrameCompose
import com.moyuxi.sound_of_the_forest.ui.pages.musicClassify.SearchMusicFrame
import com.moyuxi.sound_of_the_forest.ui.theme.SoundOfTheForestTheme
import com.moyuxi.sound_of_the_forest.viewModel.MainViewModel
import kotlinx.coroutines.launch

/**
 * 路由组件
 */
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
@Composable
fun RouteCompose(mainVM: MainViewModel, audioSB: AudioService.AudioServiceBinder?) {
    // activity级导航控制器
    val activityNavController = rememberNavController()
    val content = LocalContext.current as MainActivity
    val isPlaying by mainVM.isPlaying.observeAsState(false)
    // 应用主题，导航组件，默认导航至主活动
    BackHandler(enabled = !activityNavController.navigateUp() && isPlaying) {
        if (!activityNavController.navigateUp() && (mainVM.isPlaying.value == true)) {
            val builder = AlertDialog.Builder(content)
            builder.setTitle("提示")
            builder.setMessage("确定要关闭音乐播放？")
            builder.setNegativeButton(
                "确定"
            ) { _, _ -> content.finish() }
            builder.setNeutralButton(
                "后台播放"
            ) { _, _ -> // 既然是后台播放，就是要把当前Activity切换到后台
                content.moveTaskToBack(true)
            }
            builder.setPositiveButton("取消", null)
            val dialog = builder.create()
            dialog.show()
        }else{
            content.finish()
        }

    }
    SoundOfTheForestTheme {
        // Activity级 路由组件
        NavHost(
            navController = activityNavController, startDestination = AppRouter.Home.route
        ) {
            // 导航至主活动
            composable(AppRouter.Home.route) {
                // 抽屉级  导航控制器
                val drawerNavController = rememberNavController()
                // 音乐分类 导航控制器
                val musicClassifyNavController = rememberNavController()
                // 其它分类 导航控制器
//                val otherClassifyNavController = rememberNavController()

                // 开关抽屉用 状态
                val drawerState = rememberDrawerState(DrawerValue.Closed)
                val scope = rememberCoroutineScope()
                val openDrawer: () -> Unit = { scope.launch { drawerState.open() } }

                // 侧边栏抽屉组件
                SideDrawerCompose(
                    drawerState, scope, navigateToScreen = {
                        activityNavController.navigate(it.route) { launchSingleTop = true }
                    }, musicClassifyNC = musicClassifyNavController
                ) {//抽屉内容
                    // 抽屉组件内 组级 路由组件
                    NavHost(
                        navController = drawerNavController,
                        startDestination = DrawerRouter.MusicClassify.route
                    ) {
                        // 导航至 音乐分类项
                        composable(DrawerRouter.MusicClassify.route) {
                            MusicClassifyRouterCompose(
                                activityNavController,
                                musicClassifyNavController,
                                mainVM,
                                openDrawer
                            )
                        }
                        // 导航至 其它分类项
                        composable(DrawerRouter.OtherClassify.route) {
                            // 音乐分类项中 项级 路由组件
                        }
                    }
                }
            }
            // 导航至扫描音乐Screen
            composable(AppRouter.ScanMusic.route) {
                ScanMusicScreen(activityNavController, mainVM)
            }
            // 导航至关于Screen
            composable(AppRouter.AboutMeScreen.route) {
                AboutMeScreen(activityNavController)
            }
            //
            composable(AppRouter.ErrorInfoScreen.route) {
                ApplicationErrorScreen()
            }
        }
    }
}

/**
 * 音乐分类路由组件
 */
@Composable
fun MusicClassifyRouterCompose(
    activityNC: NavHostController,
    musicClassifyNC: NavHostController,
    mainVM: MainViewModel,
    openDrawer: () -> Unit
) {
    // 状态数据
    val data by mainVM.data.observeAsState(arrayListOf())
    var barVisible by remember { mutableStateOf(true) }
    var titleText by remember { mutableStateOf(MusicClassifyRouter.MusicList.name) }

    // 监听
    musicClassifyNC.addOnDestinationChangedListener { _, navD, _ ->
        titleText = when (navD.route) {
            MusicClassifyRouter.MusicList.route -> MusicClassifyRouter.MusicList.name
            MusicClassifyRouter.AlbumList.route -> MusicClassifyRouter.AlbumList.name
            MusicClassifyRouter.ArtistList.route -> MusicClassifyRouter.ArtistList.name
            else -> ""
        }
    }

    // 点击事件
    val cPushAll: (List<LocalMusicBean>) -> Unit = { mainVM.pushAllListToPlayerDataAndPlaying(it) }
    val cPlayBean: (LocalMusicBean) -> Unit = { mainVM.playMusicInBean(it) }
    val cAddBeanToList: (LocalMusicBean) -> Unit = { mainVM.addSongToPlayingList(it) }
    val cReSongInData: (LocalMusicBean) -> Unit = { mainVM.removeSongInDataList(it) }

    // 导航跳转
    val navToScanMusic = { activityNC.navigate(AppRouter.ScanMusic.route) }
    val navToSearchMusicBean = { musicClassifyNC.navigate(MusicClassifyRouter.SearchMusic.route) }
    val navMusicClassifyBackStack: () -> Unit = { musicClassifyNC.popBackStack() }
    val navToAlbumOrArtist: (LocalMusicBean, List<LocalMusicBean>) -> Unit = { bean, list ->
        val route = musicClassifyNC.backQueue.last().destination.route
        val args = listOf(
            Pair(
                "titleText",
                if (MusicClassifyRouter.AlbumList.route == route) bean.album else bean.singer
            ), Pair(
                "path", if (MusicClassifyRouter.AlbumList.route == route) bean.path else null
            ), Pair("localMusicBeans", list)
        )
        musicClassifyNC.navigate(MusicClassifyRouter.AlbumOrArtistList.route)
        musicClassifyNC.backQueue.lastOrNull()?.arguments?.putAll(bundleOf(*args.toTypedArray()))
    }

    // 主要页面框架
    MusicClassifyScreen(
        barVisible, mainVM, titleText, openDrawer, navToSearchMusicBean
    ) {
        // 音乐分类项中 项级 路由组件
        NavHost(
            navController = musicClassifyNC, startDestination = MusicClassifyRouter.MusicList.route
        ) {
            // 导航至 歌单
            composable(MusicClassifyRouter.MusicList.route) {
                barVisible = true
                MusicListFrameCompose(
                    data, navToScanMusic, cPushAll, cPlayBean, cAddBeanToList, cReSongInData
                )
            }
            // 导航至 专辑
            composable(MusicClassifyRouter.AlbumList.route) {
                barVisible = true
                AlbumListFrameCompose(data, navToScanMusic, navToAlbumOrArtist)
            }
            // 导航至 艺术家
            composable(MusicClassifyRouter.ArtistList.route) {
                barVisible = true
                ArtistListFrameCompose(data, navToScanMusic, navToAlbumOrArtist)
            }
            // 导航至 专辑或艺术家的详细页
            composable(MusicClassifyRouter.AlbumOrArtistList.route) {
                barVisible = false
                AlbumOrArtistListInfoComponent(
                    it.arguments?.getString("titleText") ?: "",
                    it.arguments?.getString("path") ?: "",
                    it.arguments?.get("localMusicBeans") as MutableList<LocalMusicBean>,
                    navMusicClassifyBackStack,
                    cPushAll,
                    cPlayBean,
                    cAddBeanToList,
                    cReSongInData
                )
            }
            // 导航至 搜索页
            composable(MusicClassifyRouter.SearchMusic.route) {
                barVisible = false
                SearchMusicFrame(
                    mainVM, musicClassifyNC, cPushAll, cPlayBean, cAddBeanToList, cReSongInData
                )
            }
        }
    }
}